package com.jose.photogallery;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.jose.photogallery.domain.PhotogalleryDAO;

@SuppressWarnings("serial")
public class GalleryServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		PhotogalleryDAO dao = new PhotogalleryDAO();

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		// Set proper parameters if the user is log in
		if (user != null) {
			String logoutUrl = userService.createLogoutURL("/");
			req.setAttribute("logoutUrl", logoutUrl);
			req.setAttribute("user", user);
		} else {
			String loginUrl = userService.createLoginURL("/");
			req.setAttribute("loginUrl", loginUrl);
		}

		String menu = null;

		// Default view = top
		if (req.getParameter("show") == null) {
			menu = "top";
		} else {
			menu = (String) req.getParameter("show");
		}

		// Show the photos depending on the menu selected
		if (menu.equals("top")) {
			req.setAttribute("query", dao.getTop());
		} else if (menu.equals("latest")) {
			req.setAttribute("query", dao.getLates());
		} else if (menu.equals("mypics") && (user != null)) {
			req.setAttribute("query", dao.getUserPhotos(user.getUserId()));
		} else {
			req.setAttribute("error", "Url doe not exist!");
			req.getRequestDispatcher("/WEB-INF/JSP/errorpage.jsp").forward(req,resp);
			return;
		}

		req.setAttribute("menu", menu);
		req.getRequestDispatcher("/WEB-INF/JSP/gallery.jsp").forward(req, resp);
	}
}
